'use strict';

const fs = require("fs");
const path = require("path");
const request = require("request");
const yauzl = require('yauzl');
const iconv = require('iconv-lite');

let fileName = "Linux-ia32.zip" ;
let url = "https://gitee.com/gdty/ffmpeg/raw/master/" + fileName;

let dirPath = path.join(__dirname, "");
let stream = fs.createWriteStream(path.join(dirPath, fileName));
request(url).pipe(stream).on("close", function (err) {
    console.log("文件[" + fileName + "]下载完毕");

    let zipFilePath = path.join(__dirname, fileName); // 要解压的压缩文件路径
    let outputDir = path.join(__dirname, '/'); // 解压后的输出文件夹路径

    // 创建输出目录
    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir);
    }

    // 打开 ZIP 文件
    yauzl.open(zipFilePath, { decodeStrings: false, autoClose: false }, (err, zipfile) => {
        if (err) throw err;

        zipfile.on('entry', (entry) => {
            const entryNameBuffer = Buffer.from(entry.fileName, 'binary');
            const entryName = iconv.decode(entryNameBuffer, 'gbk'); // 假设文件名是使用 GBK 编码的

            const entryOutputPath = path.join(outputDir, entryName);

            if (/\/$/.test(entry.fileName)) {
                // 创建子文件夹
                if (!fs.existsSync(entryOutputPath)) {
                    fs.mkdirSync(entryOutputPath, { recursive: true });
                }
            } else {
                // 解压文件
                zipfile.openReadStream(entry, (err, readStream) => {
                    if (err) throw err;

                    readStream.pipe(fs.createWriteStream(entryOutputPath));
                });
            }
        });

        zipfile.on('end', () => {
            console.log('解压完成！');
            fs.rmSync(fileName);
        });
    });
});



